/*
 * MultipartStream.h
 *
 *  Created on: 2017年11月8日
 *      Author: zhengboyuan
 */

#ifndef MULTIPARTSTREAM_H_
#define MULTIPARTSTREAM_H_

#include "BasicType.h"
#include "StringArray.h"
#include "SharedPtr.h"
#include <deque>


class DataStream
{
public:
	virtual ~DataStream() {}

	virtual size_t getLength() = 0;

	virtual std::istream& getStream() = 0;
};

typedef std::shared_ptr< DataStream >	DataStreamPtr;
typedef std::deque< DataStreamPtr >		DataStreamDeque;


class PartStream
{
public:
	StringMap	header;
	std::string type;
	DataStreamPtr stream;
};


typedef std::vector< PartStream >	PartStreamArray;


class MultipartStream
{
public:
	MultipartStream();
	virtual ~MultipartStream();

	/// 边界.
	const std::string& boundary() const;

	/**
	 * 添加表数据分段, 可以多次调用.
	 * @param name	名称
	 * @param data	数据
	 * @return true 表示成功
	 */
	bool addFormData(const std::string& name, const std::string& data);

	bool addFormData(const StringMap& formData);

	bool addFile(const std::string& name, const std::string& type, const std::string& filepath);

	int read(char* buffer, int size);

	int getLength();

protected:
	std::string makeBoundary();

	int makeDataStream(PartStream& partStream);
	int makeDataStream();

	int makeFirstBoundary();
	int makeLastBoundary();
	int makeMiddleBoundary();

	int readData(char* buffer, int size);

protected:
	std::string	m_boundary;
	PartStreamArray	m_parts;

	DataStreamDeque	m_dataStreams;

};

#endif /* MULTIPARTSTREAM_H_ */
